﻿using NHibernate;

using ProgressTracker.Data.Abstract;
using ProgressTracker.Data.Entities;

namespace ProgressTracker.Data.Concrete
{
    public class UserRepository : IUserRepository
    {
        ISession _session;

        public UserRepository(ISession session)
        {
            _session = session;
        }

        public bool UserExists(string email)
        {
            var results = _session.QueryOver<User>()
                .Where(x => x.Email == email);

            return results.RowCount() > 0;
        }

        public void Create(User user)
        {
            using (var transaction = _session.BeginTransaction())
            {
                _session.Save(user);
                transaction.Commit();
            }
        }

        public User GetUserByEmail(string email)
        {
            var results = _session.QueryOver<User>()
                .Where(x => x.Email == email).List();

            return results[0];
        }

        public void Save(User user)
        {
            using (var transaction = _session.BeginTransaction())
            {
                _session.Update(user);
                transaction.Commit();
            }
        }

        public void Delete(User user)
        {
            using (var transaction = _session.BeginTransaction())
            {
                _session.Delete(user);
                transaction.Commit();
            }
        }
    }
}
